// 后台脚本 - 处理点击数据的存储和统计

// 监听来自 content script 和 popup 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    switch (request.action) {
        case 'recordClick':
            recordClick(request.data);
            sendResponse({ success: true });
            break;
        case 'getStats':
            getStats().then(stats => sendResponse(stats));
            return true; // 异步响应
        case 'resetStats':
            resetStats().then(() => sendResponse({ success: true }));
            return true; // 异步响应
        default:
            sendResponse({ error: 'Unknown action' });
    }
});

// 记录点击数据
async function recordClick(clickData) {
    try {
        // 获取现有数据
        const data = await chrome.storage.local.get(['clickHistory', 'totalClicks', 'dailyClicks', 'lastResetDate']);

        // 初始化数据结构
        const clickHistory = data.clickHistory || [];
        let totalClicks = data.totalClicks || 0;
        let dailyClicks = data.dailyClicks || 0;
        const lastResetDate = data.lastResetDate || new Date().toDateString();

        // 检查是否是新的一天
        const today = new Date().toDateString();
        if (lastResetDate !== today) {
            dailyClicks = 0;
        }

        // 更新统计数据
        totalClicks++;
        dailyClicks++;

        // 添加到历史记录（保留最近 1000 条）
        clickHistory.unshift(clickData);
        if (clickHistory.length > 1000) {
            clickHistory.pop();
        }

        // 保存数据
        await chrome.storage.local.set({
            clickHistory: clickHistory,
            totalClicks: totalClicks,
            dailyClicks: dailyClicks,
            lastResetDate: today
        });

        console.log('点击已记录：', clickData);

    } catch (error) {
        console.error('记录点击失败：', error);
    }
}

// 获取统计数据
async function getStats() {
    try {
        const data = await chrome.storage.local.get(['clickHistory', 'totalClicks', 'dailyClicks', 'lastResetDate']);

        // 检查是否是新的一天
        const today = new Date().toDateString();
        const lastResetDate = data.lastResetDate || today;
        let dailyClicks = data.dailyClicks || 0;

        if (lastResetDate !== today) {
            dailyClicks = 0;
            // 更新日期
            await chrome.storage.local.set({
                dailyClicks: 0,
                lastResetDate: today
            });
        }

        return {
            totalClicks: data.totalClicks || 0,
            dailyClicks: dailyClicks,
            clickHistory: data.clickHistory || [],
            lastResetDate: lastResetDate
        };

    } catch (error) {
        console.error('获取统计数据失败：', error);
        return {
            totalClicks: 0,
            dailyClicks: 0,
            clickHistory: [],
            lastResetDate: new Date().toDateString()
        };
    }
}

// 重置统计数据
async function resetStats() {
    try {
        await chrome.storage.local.clear();
        console.log('统计数据已重置');
    } catch (error) {
        console.error('重置统计数据失败：', error);
        throw error;
    }
}

// 扩展安装或启动时的初始化
chrome.runtime.onInstalled.addListener(() => {
    console.log('点击次数记录器已安装');
});

chrome.runtime.onStartup.addListener(() => {
    console.log('点击次数记录器已启动');
});